import service from "@/utils/request";

function get(url, params) {
    return service({ url, method: 'get', params })
}

function put(url, data) {
    return service({
        url, method: 'put', data
    })
}

function sendUrl(url) {
    return service({
        url: '/http-send?url=' + url, method: 'get'
    })
}

function condition(arrs) {
    if (arrs instanceof Array) {
        return encodeURI(JSON.stringify(arrs.filter(arr => arr.val)))
    } else {
        return encodeURI(JSON.stringify([arrs]))
    }
}

function initBaseApi(modularUrl, modelUrl) {
    return {
        list(data) { return service({ url: `/${modularUrl}/${modelUrl}`, method: 'get', params: data }) },
        add(data) { return service({ url: `/${modularUrl}/${modelUrl}`, method: 'put', data }) },
        edit(data) { return service({ url: `/${modularUrl}/${modelUrl}`, method: 'post', data }) },
        remove(id) { return service({ url: `/${modularUrl}/${modelUrl}/${id}`, method: 'delete' }) },
        editStatus(data) { return service({ url: `/${modularUrl}/${modelUrl}/edit-status`, method: 'post', params: { data }}) },
        view(id) { return service({ url: `/${modularUrl}/${modelUrl}/${id}`, method: 'get' }) },
        getAttributes() { return service({ url: `/${modularUrl}/${modelUrl}/get-attributes`, method: 'post' }) }
    }
}

async function buildDict(modularUrl, modelUrl) {
    let api = initBaseApi(modularUrl, modelUrl)
    let res = await api.list({ limit: 999 })
    const content = res.records
    return content.map(item => {
        return { name: item.name, val: item.id }
    })
}

const UtilAxios = {
    condition,
    initBaseApi,
    buildDict,
    get,
    put,
    sendUrl
}

export default UtilAxios
